<template>
  <div>
    <div class="title"> {{"阶段配置 - ["+phaseData.name + "]"}}</div>
    <el-form :model="phaseData" label-width="70px" ref="ruleForm" size="small" :rules="rules" :hide-required-asterisk="true">

      <el-row :gutter="24">
        <el-col :xs="23" :sm="12" :md="12" :lg="6" :xl="6">
          <el-form-item label="阶段名称">
            <el-input v-model="phaseData.name" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="23" :sm="12" :md="12" :lg="6" :xl="6">
          <el-form-item label="阶段类型">
            <el-input v-model="phaseData.phaseType" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="23" :sm="12" :md="12" :lg="6" :xl="6">
          <el-form-item label="阶段编码">
            <el-input v-model="phaseData.sn" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="23" :sm="12" :md="12" :lg="6" :xl="6">
          <el-form-item label-width="0" style="text-align: right;" class="btnGourd">
            <el-button type="primary" size="mini" @click="handleAdd()">添 加</el-button>
            <el-button type="primary" size="mini" @click="handleEdit()">编 辑</el-button>
            <el-button type="primary" size="mini" @click="handleDel()">删 除</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <div>
        <el-row :gutter="24" style="clear:both">
          <el-col :xs="24">
            <div class="tableAuto" style="padding:0 12px">
              <el-table :data="tableData" :height="height" @row-click="rowClick" style="width:100%" border stripe v-loading="tableLoading"
                :header-cell-style="{background:'#EAEBEC'}" ref="refTable" highlight-current-row>
                <el-table-column label="" width="50" align="center">
                  <template slot-scope="scope">
                    <div>
                      <el-radio :label="scope.row.fid" v-model="radioId">&nbsp;</el-radio>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
                <el-table-column prop="paraName" show-overflow-tooltip label="数据名称"></el-table-column>
                <el-table-column prop="group" show-overflow-tooltip label="数据组">
                  <template slot-scope="scope">
                    {{parseFloat(scope.row.groups) === 0 ? '质量数据' : scope.row.groups == 1 ? '过程数据' : ''}}
                  </template>
                </el-table-column>
                <el-table-column prop="type" show-overflow-tooltip label="数据类型">
                  <template slot-scope="scope">
                    {{getDataType(scope.row.type)}}
                  </template>
                </el-table-column>
                <el-table-column prop="uom" show-overflow-tooltip :label="$t('basic.company')"></el-table-column>
              </el-table>
            </div>
          </el-col>
          <el-col :xs="24">
            <div class="pagination-area">
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 20, 50, 100]"
                :page-size="pager.pageSize" :current-page="pager.pageNum" layout="total, sizes, prev, pager, next, jumper"
                :total="pager.total">
              </el-pagination>
            </div>
          </el-col>
        </el-row>
      </div>

      <el-row :gutter="24">
        <el-col :xs="23" :sm="24" :md="24" :lg="24" :xl="24">
          <el-form-item label="备注">
            <el-input type="textarea" rows="2" v-model="phaseData.description" placeholder="" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="footerBtn">
      <el-button type="primary" size="small" :loading="loading"
        @click="handleConfirmStorage('ruleForm')">{{ $t("common.preservation") }}</el-button>
      <!-- <el-button @click="handleClose()" size="small">{{ $t("common.cancel") }}</el-button> -->
    </div>

    <el-dialog :title="title" :visible.sync="isShowAdd" :close-on-click-modal="false" :before-close="handleCloseAdd"
      :width="screenWidth > 1024 ? '30%' : '35%'" v-dialogDrag>
      <el-form :model="ruleForm" label-width="85px" ref="formName" size="small" :rules="addRules" :hide-required-asterisk="true">
        <el-row :gutter="35">
          <el-col :xs="24">
            <el-form-item label="数据名称" prop="paraName">
              <el-input type="text" v-model="ruleForm.paraName" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item label="数据类型" prop="type" class="selectClass">
              <el-select v-model="ruleForm.type" placeholder="" clearable @change="handleDataType">
                <el-option v-for="(item,index) in dataTypeList" :key="index" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" v-if="ruleForm.type != 2 && ruleForm.type != 3">
            <el-form-item :label="$t('basic.company')" prop="uom" class="selectClass">
              <el-select v-model="ruleForm.uom" placeholder="" clearable>
                <el-option v-for="(item,index) in uomIdList" :key="index" :label="item.fid" :value="item.fid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item label="数据组" prop="groups" class="selectClass">
              <el-select v-model="ruleForm.groups" placeholder="" clearable>
                <el-option v-for="(item,index) in groupList" :key="index+'i'" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item label="通讯标签" prop="attributId">
              <el-checkbox v-model="ruleForm.useAttribute" @change="changeIo">&nbsp;&nbsp;&nbsp;&nbsp;
                <el-select v-model="ruleForm.attributId" :disabled="!ruleForm.useAttribute" placeholder="" clearable>
                  <el-option v-for="(item,index) in ioAttributeList" :key="index+'i'" :label="item.name" :value="item.fid"></el-option>
                </el-select>
              </el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="24" v-if="ruleForm.type != 2 && ruleForm.type != 3">
            <el-form-item label="录入上限" prop="hi">
              <el-checkbox v-model="ruleForm.hiBool" @change="changeStatu">Hi
                <el-input type="number" :disabled="!ruleForm.hiBool" size="small" v-model="ruleForm.hi" placeholder=""
                  v-enterNumber2></el-input>
              </el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="24" v-if="ruleForm.type != 2 && ruleForm.type != 3">
            <el-form-item label="录入下限" prop="lo">
              <el-checkbox v-model="ruleForm.loBool" @change="changeStatu1">Lo
                <el-input type="number" :disabled="!ruleForm.loBool" size="small" v-model="ruleForm.lo" placeholder=""
                  v-enterNumber2></el-input>
              </el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" :loading="loadingTab"
          @click="handleConfirm('formName')">{{ $t("common.preservation") }}</el-button>
        <el-button @click="handleCloseAdd()" size="small">{{ $t("common.cancel") }}</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { formula } from "@/api/formula"
import { configure } from "@/api/configure"
export default {
  props: {
    screenWidth: Number,
    isShow: Boolean,
    phaseData: Object,
    parentFid: String
  },
  data () {
    let hiFn = (rule, value, callback) => {
      if (this.ruleForm.hiBool && !value) {
        callback(new Error('请输入录入上限'));
      } else {
        callback();
      }
    }
    let loFn = (rule, value, callback) => {
      if (this.ruleForm.loBool && !value) {
        callback(new Error('请输入录入下限'));
      } else if (parseFloat(this.ruleForm.hi) < parseFloat(value)) {
        callback(new Error('录入下限不能大于上限'));
      } else {
        callback();
      }
    }
    let uomFn = (rule, value, callback) => {
      console.log(this.ruleForm.type)
      if (this.ruleForm.type === '0' || this.ruleForm.type === '1') {
        if (!value) {
          callback(new Error('单位不能为空'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    }
    let attributeIdFn = (rule, value, callback) => {
      if (this.ruleForm.useAttribute) {
        if (!value) {
          callback(new Error('通讯标签不能为空'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    }
    return {
      height: "calc(100vh - 375px)",
      tableData: [],
      radioId: "",
      rules: {
        startDelay: [{ required: true, message: '请输入启动延时', trigger: 'blur' }],
      },
      title: "添加",
      isShowAdd: false,
      ruleForm: {
        paraName: "",
        type: "",
        uom: "",
        hiBool: false,
        loBool: false,
        groups: "",
        useAttribute: false,
        attributId: ""

      },
      dataTypeList: [{
        label: "Float",
        value: "0"
      }, {
        label: "Int",
        value: "1"
      }, {
        label: "String",
        value: "2"
      }, {
        label: "Bool",
        value: "3"
      }],
      groupList: [{
        label: "质量数据",
        value: "0"
      }, {
        label: "过程数据",
        value: "1"
      }],
      addRules: {
        paraName: [{ required: true, message: '数据名称不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '数据类型不能为空', trigger: 'change' }],
        uom: [{ validator: uomFn, trigger: 'change' }],
        groups: [{ required: true, message: '数据组不能为空', trigger: 'change' }],
        hi: [{ validator: hiFn, trigger: 'blur' }],
        lo: [{ validator: loFn, trigger: 'blur' }],
        attributId: [{ validator: attributeIdFn, trigger: 'blur' }]
      },
      loading: false,
      stepLoading: false,
      uomIdList: [],
      ioAttributeList: [],
      pager: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableLoading: false,
      loadingTab: false,
      allTable: "",
      hiBool: false,
      loBool: false
    }
  },
  created () {
    this.getUomList()
    this.getIoAttributeList()
    this.phaseIptList()
  },
  methods: {
    // 获取计量单位列表
    getUomList () {
      const param = {
        page: 1,
        size: 9999
      }
      configure.getUomList(param).then(res => {
        if (res.code == 200) {
          this.uomIdList = res.data.rows
        }
      }).catch(e => {

      })
    },
    getIoAttributeList () {
      const param = {}
      formula.getIoAttributeList(param).then(res => {
        if (res.code == 200) {
          this.ioAttributeList = res.data.rows
        }
      })
    },
    phaseIptList () {
      const param = {
        phaseId: this.parentFid,
        page: this.pager.pageNum,
        size: this.pager.pageSize
      }
      this.tableLoading = true
      formula.phaseIptList(param).then(res => {
        this.tableLoading = false
        if (res.code == 200) {
          this.allTable = res.data.rows
          this.tableData = res.data.rows.filter(item => {
            return item.paraName && this.$util.isNumber(item.type) && item.groups != 3
          })
          let item = res.data.rows.find(item => {
            return (item.target !== '' && item.target !== null) || item.groups == 3
          }) || {}
          this.fid = item.fid
          if (JSON.stringify(item) != '{}') {
            this.pager.total = res.data.total - 1
          } else {
            this.pager.total = res.data.total
          }

        }
      })
    },
    rowClick (row) {
      this.radioId = row.fid;
      this.$refs.refTable.setCurrentRow(row);
    },
    handleClose () {
      this.$emit('handleClose', 'PH_IPT')
    },
    handleDataType (val) {
      if (val == 2 || val == 3) {
        this.$set(this.ruleForm, 'uom', '')
        this.$set(this.ruleForm, 'hi', '')
        this.$set(this.ruleForm, 'lo', '')
        let fields = this.$refs['formName'].fields;
        for (let i = 0; i < fields.length; i++) {
          if (fields[i].prop == 'uom' || fields[i].prop == 'hi' || fields[i].prop == 'lo') {
            fields[i].resetFields()
          }
        }
      } else {
        this.addRules.groups[0].required = true
      }
    },
    handleAdd () {
      this.title = "添加"
      this.ruleForm = {}
      try {
        this.$refs['formName'].resetFields();
      } catch (e) { }
      this.ruleForm.loBool = false
      this.ruleForm.hiBool = false
      this.ruleForm.useAttribute = false
      this.isShowAdd = true
    },
    handleEdit () {
      if (this.radioId === '') {
        this.$message.error('请选择修改数据');
        return
      }
      this.title = "编辑"
      formula.phaseIptFind(this.radioId).then(res => {
        if (res.code == 200) {
          this.ruleForm = Object.assign({}, res.data)
          this.ruleForm.type = res.data.type + ""
          this.ruleForm.hiBool = res.data.hi ? true : false
          this.ruleForm.loBool = res.data.lo ? true : false
          this.ruleForm.useAttribute = res.data.useAttribute ? true : false
          this.isShowAdd = true
        }
      })
    },
    handleCloseAdd () {
      this.isShowAdd = false
    },
    handleConfirm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let param = {}
          if (this.ruleForm.paraName == '启动延时') {
            this.$message.error('名称已存在');
            return
          }
          if (this.title == '添加') {
            param = {
              paraName: this.ruleForm.paraName,
              uom: this.ruleForm.uom,
              groups: this.ruleForm.groups,
              hi: this.ruleForm.hiBool ? this.ruleForm.hi : '',
              lo: this.ruleForm.loBool ? this.ruleForm.lo : '',
              type: this.ruleForm.type,
              phaseId: this.parentFid,
              attributId: this.ruleForm.attributId,
              useAttribute: this.ruleForm.useAttribute == true ? 1 : 0
            }
          } else {
            param = Object.assign({}, this.ruleForm)
            param.useAttribute = this.ruleForm.useAttribute ? 1 : 0
          }
          this.loadingTab = true
          formula.phaseIptAdd(param, this.title).then(res => {
            this.loadingTab = false
            if (res.code == 200) {
              this.isShowAdd = false
              this.phaseIptList()
            } else {
              this.$message.error(res.msg);
            }
          })
        } else {
          return false
        }
      })
    },
    async handleDel () {
      if (this.radioId === '') {
        this.$message.error('请选择要删除的数据');
        return
      }
      formula.phaseIptFind(this.radioId).then(res => {
        if (res.code == 200) {
          let fid = res.data.fid
          let that = this
          this.$customConfirm({
            onok () {
              formula.phaseIptRemove(fid).then(res => {
                if (res.code == 200) {
                  that.phaseIptList()
                  that.radioId = ''
                  that.$message({ duration: 1000, type: 'success', message: '删除成功!' });
                }
              })
            }
          });
        }
      })
    },
    handleConfirmStorage (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let param = {
            fid: this.phaseData.fid,
            name: this.phaseData.name,
            type: this.phaseData.type,
            sn: this.phaseData.sn,
            description: this.phaseData.description,
          }
          this.loading = true
          configure.phaseDefineAdd(param, '编辑').then(res => {
            this.loading = false
            if (res.code == 200) {
              this.$message({ duration: 1000, type: 'success', message: '保存成功!' });
              this.$emit('uptionList')
            }
          }).catch(e => {
            this.loading = false
          })
        }
      })

    },
    handleSizeChange (val) {
      this.pager.pageSize = val
      this.phaseIptList()
    },
    handleCurrentChange (val) {
      this.pager.pageNum = val;
      this.phaseIptList()
    },
    getDataType (id) {
      if (!id && id !== 0) return ''
      return this.dataTypeList.find(item => item.value == id).label
    },
    changeStatu () {
      if (!this.ruleForm.hiBool) {
        this.ruleForm.hi = ''
      }
      this.$forceUpdate()
    },
    changeStatu1 () {
      if (!this.ruleForm.loBool) {
        this.ruleForm.lo = ''
      }
      this.$forceUpdate()
    },
    changeIo (val) {
      if (!val) {
        this.ruleForm.attributId = ''
      }
      this.$forceUpdate()
    }
  }
}
</script>

<style scoped>
@media screen and (max-width: 1024px) {
  .tableAuto {
    width: 100%;
    overflow: auto;
  }
}
.rightAdd {
  color: #00a09d;
  cursor: pointer;
  font-size: 20px;
}
.selectClass >>> .el-select {
  width: 100%;
}
@media screen and (max-width: 1200px) {
  .btnGourd {
    text-align: left !important;
  }
}
.pagination-area {
  padding: 10px;
}
.append >>> .el-input-group__append {
  padding: 0 10px;
}
/* .seqNo >>> .el-input__inner{
        padding: 0 0 0 12px;
    } */
.btnGourd >>> .el-button--mini {
  padding: 7px 11px;
}
.title {
  line-height: 35px;
  background: #3b2e58;
  color: #fff;
  padding: 0 15px;
  font-size: 14px;
  margin-bottom: 10px;
}
.footerBtn {
  text-align: right;
}
</style>